package com.joker.service;


import com.joker.util.FtpUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 图片上传服务
 * <p>Title: PictureServiceImpl</p>
 */
@Service
public class PictureService{

    @Value("${FTP_ADDRESS}")
    private String FTP_ADDRESS;
    @Value("${FTP_PORT}")
    private Integer FTP_PORT;
    @Value("${FTP_USERNAME}")
    private String FTP_USERNAME;
    @Value("${FTP_PASSWORD}")
    private String FTP_PASSWORD;
    @Value("${FTP_BASE_PATH}")
    private String FTP_BASE_PATH;
    @Value("${IMAGE_BASE_URL}")
    private String IMAGE_BASE_URL;

    private static String LOCAL_CHARSET="GBK";

    // @Override
    public Map uploadPicture(MultipartFile uploadFile) {
        Map resultMap = new HashMap<>();
        try {
            //生成一个新的文件名
            //取原始文件名
            String oldName = uploadFile.getOriginalFilename();
            //生成新文件名
            //UUID.randomUUID();
            String Suffix = oldName.substring(oldName.lastIndexOf("."));
            //保存的文件名
            String newName = UUID.randomUUID()+Suffix;
            // String newName = IDUtils.genImageName();
            // newName = newName + oldName.substring(oldName.lastIndexOf("."));
            //图片上传
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
            String imagePath=simpleDateFormat.format(new Date());

            System.err.println(imagePath);
            System.err.println(newName);


            boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD,
                    FTP_BASE_PATH, imagePath, newName, uploadFile.getInputStream());
            //返回结果
            if(!result) {
                resultMap.put("error", 1);
                resultMap.put("message", "文件上传失败");
                return resultMap;
            }
            resultMap.put("error", 0);
            resultMap.put("url", IMAGE_BASE_URL + imagePath + "/" + newName);
            return resultMap;

        } catch (Exception e) {
            resultMap.put("error", 1);
            resultMap.put("message", "文件上传发生异常");
            return resultMap;
        }
    }
    public void sendFtp(File file) throws IOException {
        FTPClient ftpClient=new FTPClient();
        if (connectServer(ftpClient)){
            String ZN_CHARSET="GBK";
            try {
                String s = new String(file.getName().getBytes(ZN_CHARSET), StandardCharsets.ISO_8859_1);
                if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))){
                    LOCAL_CHARSET="UTF-8";
                }
                ftpClient.setControlEncoding(LOCAL_CHARSET);
                ftpClient.changeWorkingDirectory(FTP_ADDRESS+FTP_PORT);
                ftpClient.setBufferSize(1024);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();
                boolean b = ftpClient.storeFile(s, new FileInputStream(file));
                System.out.println(b);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                ftpClient.disconnect();
            }
        }
    }

    private boolean connectServer(FTPClient ftpClient) {
        boolean isSuccess=true;
        try {
            ftpClient.connect(FTP_ADDRESS, FTP_PORT);
            isSuccess=ftpClient.login(FTP_USERNAME, FTP_PASSWORD);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("连接服务器失败");
        }
        return isSuccess;
    }

}
